<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :replaceFields="{ title: 'menuName', key: 'id', children: 'childList' }"
          checkable
          toolbar
          :title="t('routes.table.roleManagement.menuAssign')"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { getMenuList } from '/@/api/demo/menu';
  import { AddFunctionRole, UpdateFunctionRole } from '/@/api/demo/system';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const { createMessage } = useMessage();

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await getMenuList({ status: -1 })) as any as TreeItem[];
    }
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue(data.record);
    }
    updateSchema([
      {
        field: 'id',
        dynamicDisabled: !!unref(isUpdate),
      },
    ]);
  });

  const getTitle = computed(() =>
    !unref(isUpdate)
      ? t('routes.table.roleManagement.addRole')
      : t('routes.table.roleManagement.editRole'),
  );

  async function handleSubmit() {
    try {
      const values = await validate();
      if (unref(isUpdate)) {
        await UpdateFunctionRole(values);
        createMessage.success(t('common.editSuccessText'));
      } else {
        await AddFunctionRole(values);
        createMessage.success(t('common.addSuccessText'));
      }
      setDrawerProps({ confirmLoading: true });
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
